package leetcode8

import "math"

func myAtoi(s string) int {
	if len(s) == 0 {
		return 0
	}
	var (
		intMax = math.MaxInt32
		res    int
		i      int
		sign   = 1
	)

	// 找到第一位不为空的字符
	for i = range s {
		if s[i] != ' ' {
			break
		}
	}

	if s[i] == '-' {
		sign = -1 // 负数
		i++
	} else if s[i] == '+' {
		i++
	}

	for ; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			break
		}
		res = res*10 + int(s[i]-'0')
		if res > intMax {
			if sign == -1 {
				res = intMax*sign - 1
			} else {
				res = intMax
			}
			return res
		}
	}
	return res * sign
}
